import groovy.util.*

def fout = new PrintWriter(new BufferedWriter(new FileWriter("flyphenotypes.txt")))
def foutplain = new PrintWriter(new BufferedWriter(new FileWriter("flyphenotypes-names.txt")))

def flyfile = new File("allele_phenotypic_data_fb_2012_01.tsv")
def flyont = new File("flybase_controlled_vocabulary.obo")
def flyant = new File("fly_anatomy.obo")

def chadofile = new File("FBal.xml")

def entries = new XmlSlurper().parse(chadofile)

def map = [:]
entries.allele.each { allele ->
  def id = allele.id.text()
  allele.related_feature.each { rel ->
    if ((rel.relationship_type.text()=="alleleof") && (rel.type=="gene")) {
      map[id] = rel.id.text()
      foutplain.println(rel.id.text()+"\t"+rel.synonym.name.text())
    }
  }
}

def term2id = [:]
def term = ""
def id = ""
flyont.eachLine {line ->
  if (line.startsWith("id:")) {
    id = line.substring(3).trim()
  }
  if (line.startsWith("name:")) {
    term = line.substring(5).trim()
  }
  if (line.startsWith("[Term]")) {
    term2id[term] = id
  }
}
flyant.eachLine {line ->
  if (line.startsWith("id:")) {
    id = line.substring(3).trim()
  }
  if (line.startsWith("name:")) {
    term = line.substring(5).trim()
  }
  if (line.startsWith("[Term]")) {
    term2id[term] = id
  }
}

flyfile.splitEachLine ("\t") { line ->
  line[2]?.split("\\|").each {
    if (term2id[it]!=null) {
      fout.println(line[1]+"\t"+term2id[it]+"\t"+it)
      foutplain.println(line[1]+"\t"+line[0])

      if (map[line[1]]!=null) {
	fout.println(map[line[1]]+"\t"+term2id[it]+"\t"+it)
      }

    } else if (it.startsWith("GO")) {
      def q = "GO:"+it.substring(2,9)
      fout.println(line[1]+"\t"+q+"\t"+it)
      foutplain.println(line[1]+"\t"+line[0])

      if (map[line[1]]!=null) {
	fout.println(map[line[1]]+"\t"+q+"\t"+it)
      }
    }
  }
}
fout.flush()
fout.close()
foutplain.flush()
foutplain.close()
